// pages/video/video.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    videoList: [],
    activeIndex: 0,
    videoContexts: [],
    isPlaying: true,
    pageNum: 1,
    pageSize: 10
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.fetchVideoList(1);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { activeIndex, videoContexts, isPlaying } = this.data;
    const currentVideo = videoContexts[activeIndex];
    currentVideo.play();  // 继续播放
    this.setData({ isPlaying: true });
  },

  onSwiperChange(e) {
    const newIndex = e.detail.current;
    const { videoContexts, activeIndex } = this.data;
    // 暂停上一个视频
    if (videoContexts[activeIndex]) {
      videoContexts[activeIndex].pause();
    }
    // 播放新视频
    if (videoContexts[newIndex]) {
      videoContexts[newIndex].play();
      this.setData({ isPlaying: true });
    }
    // 更新当前索引
    this.setData({ activeIndex: newIndex });
    // 检查是否滑动到倒数第二个视频
    if (newIndex === this.data.videoList.length - 2) {
      const nextPageNum = this.data.pageNum + 1;
      this.fetchVideoList(nextPageNum, true);
    }
    let collectionId = this.data.videoList[activeIndex].collectionId
    app.$http.get('/app/collection/'+collectionId).then(res=>{
      let collection = res.data
      collection.views = collection.views + 1
      app.$http.put('/app/collection/update', collection)
    })
  },

  togglePlay() {
    const { activeIndex, videoContexts, isPlaying } = this.data;
    const currentVideo = videoContexts[activeIndex];
    if (isPlaying) {
      currentVideo.pause(); // 暂停当前视频
    } else {
      currentVideo.play();  // 继续播放
    }
    this.setData({ isPlaying: !isPlaying }); // 切换状态
  },

  /**
   * 封装获取视频列表的方法
   */
  fetchVideoList(pageNum, isLoadMore = false) {
    app.$http.get('/app/media/list', { pageNum, pageSize: this.data.pageSize, mediaType: 2}).then(res => {
      let newVideoList = [];
      if (isLoadMore) {
        newVideoList = [...this.data.videoList, ...this.randomSortArray(res.data.records)];
      } else {
        newVideoList = this.randomSortArray(res.data.records)
      }
      this.setData({
        videoList: newVideoList,
        pageNum: pageNum,
        videoContexts: newVideoList.map((_, index) => {
          return wx.createVideoContext(`video${index}`);
        })
      });
      // 首次加载或刷新时自动播放第一个视频
      if (!isLoadMore && newVideoList.length > 0) {
        this.data.videoContexts[0].play();
      }
      let collectionId = this.data.videoList[0].collectionId
      app.$http.get('/app/collection/'+collectionId).then(res=>{
        let collection = res.data
        collection.views = collection.views + 1
        app.$http.put('/app/collection/update', collection)
      })
    })
    .catch(error => {
      console.error('获取视频列表失败:', error);
    });
  },
  randomSortArray(myArray) {
    const array = myArray;
    const len = array.length;
    for (let i = len - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      // 交换元素
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  }
})